import { ref } from 'vue'

export const useWebSocket = (taskStore) => {
    const ws = ref(null)

    // 新增：订阅所有活动任务的方法
    const subscribeToActiveTasks = () => {
        console.log('Current active tasks:', taskStore.activeTasks)
        if (taskStore.activeTasks && taskStore.activeTasks.length > 0) {
            taskStore.activeTasks.forEach(task => {
                console.log('Subscribing to task:', task.taskId)
                subscribeToTask(task.taskId)
            })
        } else {
            console.log('No active tasks to subscribe to')
        }
    }

    const connectWebSocket = () => {
        ws.value = new WebSocket('wss://admin.chen2586.top/ws/crawler')

        ws.value.onopen = async () => {
            console.log('WebSocket connected')
            // 连接后先获取最新的任务列表
            await taskStore.fetchCrawlerList()
            // 然后订阅任务
            subscribeToActiveTasks()
        }

        ws.value.onmessage = (event) => {
            const taskUpdate = JSON.parse(event.data)
            updateTaskStatus(taskUpdate)
        }

        ws.value.onclose = () => {
            console.log('WebSocket disconnected')
            // 可以在这里添加重连逻辑
            setTimeout(connectWebSocket, 3000)
        }

        ws.value.onerror = (error) => {
            console.error('WebSocket error:', error)
        }
    }

    const subscribeToTask = (taskId) => {
        if (ws.value?.readyState === WebSocket.OPEN) {
            console.log('Sending subscribe message for task:', taskId)
            ws.value.send(JSON.stringify({
                action: 'subscribe',
                taskId: taskId
            }))
        } else {
            console.warn('WebSocket not ready, cannot subscribe to task:', taskId)
        }
    }

    const unsubscribeFromTask = (taskId) => {
        if (ws.value?.readyState === WebSocket.OPEN) {
            ws.value.send(JSON.stringify({
                action: 'unsubscribe',
                taskId: taskId
            }))
        }
    }

    const updateTaskStatus = (taskUpdate) => {
        // 更新store中的任务状态
        const taskIndex = taskStore.activeTasks.findIndex(
            task => task.taskId === taskUpdate.taskId
        )

        if (taskIndex !== -1) {
            taskStore.activeTasks[taskIndex] = {
                ...taskStore.activeTasks[taskIndex],
                ...taskUpdate,
                canStop: taskUpdate.status === 'RUNNING',
                canDelete: true
            }
        }
    }

    const closeWebSocket = () => {
        if (ws.value) {
            ws.value.close()
            ws.value = null
        }
    }

    return {
        connectWebSocket,
        subscribeToTask,
        unsubscribeFromTask,
        closeWebSocket,
        ws,
        subscribeToActiveTasks
    }
}